#!bin/sh

function check_branch()
{
    [ "x$1" ==  "x" ] && echo branch is not fit now and will exit && exit 1
    echo have branch $1
    [ "$1" == "r3.0.0_feature" ] && tmp_tag=t3.0.0_yifengzhong_1.0
    [ "$1" == "r5.4.0_kumiao_bugfix" ] && tmp_tag=t5.4.0_kumiao_1.0
    [ "$1" == "r5.4.0_feature_huashu" ] && tmp_tag=t5.4.0_huashu_1.0
    [ "$1" != "r3.0.0_feature" -a "$1" != "r5.4.0_kumiao_bugfix"  -a "$1" != "r5.4.0_feature_huashu"  ] && tmp_tag=`echo $1 |sed s/^./t/g` #把首字母换成t

    echo tmp_tag=$tmp_tag
    origin_tag=tag_$tmp_tag
    echo origin_tag=$origin_tag
    git tag --sort=committerdate |grep $tmp_tag >zbuild_tmp
    echo branch $1 tag as follow:
    cat zbuild_tmp
    lastest_tag=`tail -n 1 zbuild_tmp`
    [ "x$lastest_tag" != "x" ] && echo util.sh lastest_tag is $lastest_tag
    [ "x$lastest_tag" == "x" ] && echo util.sh lastest_tag is null
    echo util.sh lastest_tag is $lastest_tag
    echo $lastest_tag > zbuild_tmp
}

function pre_build()
{
    if [ -f .gradle/2.14.1/taskArtifacts/cache.properties.lock  ];then
        echo gradle/2.14.1/taskArtifacts have cache.properties.lock and will delete .lock
        mv .gradle/2.14.1/taskArtifacts/cache.properties.lock .gradle/2.14.1/taskArtifacts/cache.properties
    fi

    if [ ! -f gradle.properties  ];then
        echo have no gradle.properties and create it
        #touch gradle.properties
        #chmod 777 gradle.properties
    else
        #持续集成环境不推荐开启gradle demon,详细参考gradel demo 官网https://docs.gradle.org/2.14.1/userguide/gradle_daemon.html
        echo CI cannot set demon enable
        #sed -i 's/org.gradle.daemon=true/org.gradle.daemon=false/g' gradle.properties
    fi
}

function change_channel()
{
    if [ "$1" == "All" ] ; then
        echo build all channels and need some time.....
    else
        fit_flag=`grep "$1 {}" $2/build.gradle `
        if [ "x$fit_flag" == "x" ];then
            change_line=`grep -rn "productFlavors {"  $2/build.gradle |awk -F ":" '{print $1}'`
            echo fit "productFlavors {"   line is $change_line and insert after $change_line  new channel $1
            sed -i "$change_line"'a\'"$1 {}" $2/build.gradle
        else
            echo $2/build.gradle already  channel $1
        fi
        echo check $2/build.gradle add result :`grep "$1 {}" $2/build.gradle`
    fi
}

function send_sdk_channel()
{
    sendsdk_old_config="CHANNEL_NAME = \"lebocast\""
    sendsdk_new_config="CHANNEL_NAME = \"$1\""
    echo old config=$sendsdk_old_config and new config=$sendsdk_new_config
    sendsdk_flag=`grep "$sendsdk_new_config" sdk/src/main/java/com/hpplay/dataupload/StatisticUpload.java `
    echo new config flag=$sendsdk_flag

    if [ "x$sendsdk_flag" == "x" ];then
        echo have no new chennel $1 and need to add it
        sed -i s/"$sendsdk_old_config"/"$sendsdk_new_config"/g sdk/src/main/java/com/hpplay/dataupload/StatisticUpload.java
        checkss_new_config=`grep "$sendsdk_new_config" sdk/src/main/java/com/hpplay/dataupload/StatisticUpload.java`
        echo checkss_new_config=$checkss_new_config
    else
        echo $sendsdk_old_config is right and no need to change
    fi
}


function send_app_channel()
{
    send_app_flag=`grep "$1 {" app/build.gradle`
    echo send_app_flag=$send_app_flag
    if [ "x$send_app_flag" == "x" ];then
        echo not find and need add  new channel $1 to tvassistant/build.gradle
        sed -i s/lebotest/$1/g app/build.gradle
        echo check again as follow:
        echo `grep $1 app/build.gradle`
    else
        echo already have this channel at app/build.gradle
    fi
}

function recsdk_mi ()
{
    echo reciever sdk mi action.....
    old_config="SO_IJK_NEEDDONWLOAD = false"
    new_config="SO_IJK_NEEDDONWLOAD = true"
    echo old_config=$old_config and new_config=$new_config
    old_config_flag=`grep "$old_config" sdk/src/com/hpplay/happyplay/BuildConfig.java`
    echo old_config_flag=$old_config_flag

    if [ "x$old_config_flag" != "x" ];then
        echo change old_config to new_config
        sed -i s/"$old_config"/"$new_config"/g sdk/src/com/hpplay/happyplay/BuildConfig.java
        check_new_config=`grep "$new_config" sdk/src/com/hpplay/happyplay/BuildConfig.java`
        echo check_new_config=$check_new_config
    else
        echo $old_config is right and no need to change
    fi
}

function rec_sdk_rename()
 {
    for mfile in `cat $1`
    do
        echo modify file $mfile
        tail_string=`echo $mfile |awk -F 'hpplay-sdk' '{print $2}'`
        echo tail_string is $tail_string
        mv target/hpplay-sdk$tail_string target/hpplay-sdk-$2"$tail_string"
    done
    echo files new name as follow:
    ls target/  |grep hpplay-sdk
 }

function upload_file()
{
    dst_dir=$1
    ftp_dir=$2

    [ -d $ftp_dir ] && rm -rf $ftp_dir
    mkdir $ftp_dir
    [ ! -d target ] ||  [ "x`ls target`" == "x" ] && echo have no target or target is empty and will exit && exit 1 #target目录不存在或者目录为空
    cp -rn  target/* $ftp_dir/

    ls $ftp_dir
    #create ftp remote dir
    ftp_pwd=$dst_dir/$ftp_dir
    curl -u aolingli:ALL1234! ftp://192.168.8.251/output/$ftp_pwd/ --ftp-create-dirs #创建远程目录
    echo upload file under $ftp_dir and upload to $dst_dir
    [ ! -d $ftp_dir ] || [ "x`ls $ftp_dir`" == "x" ] && echo $ftp_dir not exsit or empty and will exit && exit 1
    cd $ftp_dir
    for upload_file in `ls`
    do
        echo upload_file=$upload_file
        if [ -d "$upload_file" ];then #如果上传文件为文件夹，则先压缩
            echo "$upload_file" is a directory and need to compress
            zip -q -r "$upload_file".zip "$upload_file"
            #另有一种压缩命名pigz,多线程压缩，效率更高，使用如下
            #tar cvf - "$upload_file" | pigz -9 -p 24 > "$upload_file".tgz
            rm "$upload_file" -rf
            upload_file="$upload_file".zip
         fi
         curl -u aolingli:ALL1234! -T "$upload_file"  ftp://192.168.8.251/output/$ftp_pwd/
    done
    echo ftp_path="ftp://192.168.8.251/output/$ftp_pwd/"
    echo jenkins ftp path："ftp://192.168.8.251/output/$ftp_pwd/" > ../result_ftp_path.txt #用于邮件发送时，附件中指定ftp路径
    echo "upload Done. Total costs $cost seconds."
}



function get_build_result ()
{
    echo check scripts build resutlt
     #如果打包过程输出重定向文件build_result中有‘BUILD FAILED’字段或者'FAILED'字段，那么表示构建失败，退出
    if [ "x`grep -rn "BUILD FAILED" build_result`" != "x" -o "x`grep -rn "FAILED" build_result`" != "x" ];then
        echo build status is BUILD FAILED or FAILED, so exit
        exit 1
    fi
}

function rec_app_gimi()
{
    grep -rn "com.hpplay.happyplay.aw$" app/src/main/AndroidManifest.xml
    sed -i s/"com.hpplay.happyplay.aw\">"/"com.hpplay.happyplay.aw\"  android:sharedUserId=\"android.uid.system\">"/g  app/src/main/AndroidManifest.xml
    echo change check as follow:
    flag_fit_gimi=`grep -rn "android:sharedUserId=\"android.uid.system\"" app/src/main/AndroidManifest.xml`
    if [ "x$flag_fit_gimi" == "x" ];then #修改失败，未找到添加的字符串
        echo not find modify string android:sharedUserId=\"android.uid.system\" and exit
         exit 1
    else
        echo find modify string android:sharedUserId=\"android.uid.system\" as follow:
        grep -rn "android:sharedUserId=\"android.uid.system\"" app/src/main/AndroidManifest.xml
    fi
}

function send_email()
 {
     job_path="/root/.jenkins/jobs"
     email_jenkins="http://192.168.8.246:8080/jenkins/job"
     config_file=$job_path/$1/config.xml
     echo email trigger user $2
     echo config_file=$config_file
     grep -rn "ExtendedEmailPublisher>" $config_file
     email_old_line=`grep -rn "ExtendedEmailPublisher>" $config_file |awk -F ":" '{print $1 }'`
     echo email_old_line=$email_old_line
     email_fit_line=`expr $email_old_line - 1`
     email_fit_con=`sed -n "$email_fit_line"p $config_file`
     echo line $email_fit_line content is $email_fit_con
    #如果触发者是admin或者是自动触发的，如果邮件发送关掉了，那么打开开关，发送邮件
    #如果邮件发送者不是admin也不是自动触发，如果邮件功能打开了，那个关闭开关，不发送邮件
     if  [ "$2" == "admin" -o "$2" == "SCMTrigger" -o "$2" == "Timer" ] ;then
          echo   trigger is admin ,need to send email
    #使用字符串截取#*<来截取<右边的所有字符串判断
         if [ "${email_fit_con#*<}" == "disabled>true</disabled>" ] ;then
             echo but default email send function is disabled, so need to open it
             sed -i ""$email_fit_line"c <disabled>false</disabled>" $config_file #整行替换，关闭禁用开关
             curl -u admin:wangzp@360 -X POST $email_jenkins/$1/reload #重载配置
         else
             echo  default email send function is opened ,great !
         fi
     else
        echo trigger is not admin, donot need to send email
        if [ "${email_fit_con#*<}" == "disabled>false</disabled>" ];then
            echo but default email send function is opened ,so need to close it
            sed -i ""$email_fit_line"c <disabled>true</disabled>" $config_file #整行替换，打开禁用开关
            curl -u admin:wangzp@360 -X POST $email_jenkins/$1/reload #重载配置
        else
            echo  default email send function is closed ,great !
        fi
     fi

     email_fit_con=`sed -n "$email_fit_line"p $config_file` #显示配置行
     echo line  $email_fit_line new content is $email_fit_con
 }


 function replace_channel_conf()
 {
    echo get apk="$1" and channel=$2 and conf_file=$3 and repo=$4
    cur_path=`pwd`
    conf_file=$3
    aapt_command="/usr/local/scripts/build_scripts/sign_apk_tool/aapt"
    rec_xor_flag=0
    send_xor_flag=0
    tob_rec_xor_flag=0
    [ -d tmp_target ] && rm -rf tmp_target
    mkdir tmp_target
    cp target/$1 tmp_target/
    cd tmp_target
    cp /usr/local/scripts/build_scripts/$conf_file ./
    appid_flag=`grep "^$2:" $conf_file `
    [ "x$appid_flag" == "x" ] && echo not find the appid $2 in $conf_file , fail. && exit 1
    tmp_line2=`grep -rn "^$2:" $conf_file |awk -F ":" '{print $1}'` #获取channel对应的行
    tmp_line3=`expr $tmp_line2 + 1` #渠道行对应的下一行就是appid
    appid=`sed -n "$tmp_line3"p $conf_file |awk -F "=" '{print $2}'` #显示appid行对应的appid
    tmp_line4=`expr $tmp_line2 + 2` #渠道行对应的下下行就是secret
    app_secret=`sed -n "$tmp_line4"p $conf_file |awk -F "=" '{print $2}'` #显示secret行对应的secret
    original_secret=$app_secret
    papk_name=`ls |grep ".apk"
    echo papk_name=$papk_name`
    pkg_version=`$aapt_command dump badging $papk_name |grep package |awk -F  "versionCode=" '{print $2}' |awk -F " " '{print $1}' |sed s/"'"//g`
    echo pkg version is $pkg_version
    [ "$4" == "rec_app" -a $pkg_version -ge 808080110  ] && rec_xor_flag=1 #接收端app版本号大于等于808080110的要特殊处理
    [ "$4" == "send_app" -a $pkg_version -ge 30118 ] && send_xor_flag=1 #发送端app版本号大于等于30118的要特殊处理
    [ "$4" == "rec_app_tob" ] && tob_rec_xor_flag=1 #接收端tob app要特殊处理
    echo =======rec_xor_flag=$rec_xor_flag,send_xor_flag=$send_xor_flag,tob_rec_xor_flag=$tob_rec_xor_flag=========
    if [ "$rec_xor_flag" == "1" -o "$send_xor_flag" == "1" -o "$tob_rec_xor_flag" == "1" ]; then
        echo "rec app pkg version >= 808080110 or send app pkg version >= 30118 and ToBAndroidReceiver repo need deal with secret "
        echo use xor enc secret $original_secret
        xor_key=39
        resut_sec=""
        for (( secret_el=1;secret_el <= `echo ${#app_secret}`;secret_el++)) #循环次数=字符串长度
        do
            less_el=`expr $secret_el - 1`
            secret_son=${app_secret:$less_el:1} #显示每个字符串，一次循环显示一个
            [ $secret_son == "a" ] && secret_son=97 #遇到字母转换成数字
            [ $secret_son == "b" ] && secret_son=98
            [ $secret_son == "c" ] && secret_son=99
            [ $secret_son == "d" ] && secret_son=100
            [ $secret_son == "e" ] && secret_son=101
            [ $secret_son == "f" ] && secret_son=102
            son_xor=`echo $[$secret_son^$xor_key]` #单个字符和密钥做异或
            resut_sec=$resut_sec-$son_xor #拼接异或结果
        done
        app_secret=${resut_sec:1} #不显示最后拼接结果的第一个字符
        echo xor secret=$app_secret
    else
        echo old version need not to enc #之前的老版本号的不需要特殊处理
    fi
    mkdir apk_output
    mkdir META-INF
    touch META-INF/appid_$appid #以appid,channel,secret来命名新建的文件
    touch META-INF/secret_$app_secret
    touch META-INF/channel_$2
    echo new MRTA-INF file as follow:`ls META-INF`

    new_apk_name=`ls |grep ".apk$" |awk -F ".apk" '{print $1}' `
    echo unzip app name=$new_apk_name
    echo zip add null file to "$new_apk_name".apk
    zip -m "$new_apk_name".apk ./META-INF/* #追压上面的三个空文件到apk中
    time_now=`date "+%m%d%H%M"`
    new_apk_name2=`ls |grep ".apk$" |awk -F ".apk" '{print $1}' |sed s/happytest/$2/g `
    echo new_apk_name2=$new_apk_name2
    echo ==================zipalign===================
    zipalign_command="/usr/local/sdk/build-tools/25.0.3/zipalign"
    $zipalign_command -v 4 "$new_apk_name".apk apk_output/"$new_apk_name2".apk  #优化压缩
    rm "$new_apk_name".apk
    upload_app=`ls apk_output`
    cd apk_output
    echo echo zip empty file to apk as follow:
    mkdir unzip_apk
    unzip  -q "$upload_app" -d unzip_apk/
    ls unzip_apk/META-INF/
    [ ! -f unzip_apk/META-INF/appid_$appid ] && echo target file appid_$appid not in unzip META-INF ,fail. && exit 1
    echo target file appid_$appid in unzip META-INF ,success!

    echo =======rec_xor_flag=$rec_xor_flag,send_xor_flag=$send_xor_flag,tob_rec_xor_flag=$tob_rec_xor_flag=========
    if [ "$rec_xor_flag" == "1" -o "$send_xor_flag" == "1" -o "$tob_rec_xor_flag" == "1" ]; then
        echo "rec app pkg version >= 808080110 or send app pkg version >= 30118  and ToBAndroidReceiver repo need deal with secret"
        resut_sec_son=""
        [ ! -f unzip_apk/META-INF/secret_"$app_secret" ] && echo file is not exsit  and exit 1 && exit 1
        resut_sec=`ls unzip_apk/META-INF/secret_"$app_secret" |awk -F "secret_" '{print $2}' `
        echo xor_secret=$resut_sec
        echo $resut_sec  | sed s/"-"/\\n/g > son.txt
        for son_el in `cat son.txt`
        do
            son_el_xor=`echo $[$son_el^$xor_key]`
            #[ $son_el_xor -ge 65 ] &&  son_el_xor=`echo $son_el_xor | awk '{printf("%c", $1)}'` #数字转ascii(备用A-Z,a-z)
            [ $son_el_xor == 97 ] && son_el_xor="a"
            [ $son_el_xor == 98 ] && son_el_xor="b"
            [ $son_el_xor == 99 ] && son_el_xor="c"
            [ $son_el_xor == 100 ] && son_el_xor="d"
            [ $son_el_xor == 101 ] && son_el_xor="e"
            [ $son_el_xor == 102 ] && son_el_xor="f"
            resut_sec_son="$resut_sec_son""$son_el_xor"
        done

        echo dec secret=$resut_sec_son
        echo enc secret=$original_secret
        [ $resut_sec_son != $original_secret ]  && echo dec secret is not equal to origin secret and exit && exit 1
        echo dec secret is the same as origin secret,success!
    else
        echo old version need not to enc
        [ ! -f unzip_apk/META-INF/secret_"$app_secret" ] && echo have no unzip_apk/META-INF/secret_"$app_secret" && exit 1
        new_sec=`ls unzip_apk/META-INF/secret_"$app_secret" |awk -F "secret_" '{print $2}' `
        echo new_sec=$new_sec
        echo original_secret=$original_secret
         [ $new_sec != $original_secret ] && echo not enc unzip secret not euqla to original_secret,failed. && exit 1
         echo not enc unzip secret = original_secret,success
    fi
    echo will upload file "$upload_app" to ftp
    echo upload file info as follow:
    du -sh $upload_app
    cp "$new_apk_name2".apk $cur_path/target
    cd  $cur_path
    echo ================end deal with "$new_apk_name2".apk======================
 }


function phoenix_app_special_channels()
{
    tool_path="/usr/local/scripts/build_scripts/sign_apk_tool"
    echo app_name=$1  channel=$2
    if [ "$2" != "alibaba" -a "$2" != "damai_inner" -a "$2" != "damai_oversea" -a "$2" != "skyworthbox" -a "$2" != "imilab" -a "$2" != "xiaomi" \
        -a "$2" != "jianguo_up" -a "$2" != "dangbei_touying" -a "$2" != "dangbei_ty" -a "$2" != "jsyd" ]; then
        echo not alibaba, damai_inner,damai_oversea,skyworthbox,imilab,xiaomi,jianguo_up,dangbei_touying,dangbei_ty,jsyd channel, so do nothing and return
        return #只处理以上渠道，其他渠道不处理
    fi
    if [ -d sign_apk_tool ];then
        echo delete sign_apk_tool
        rm sign_apk_tool -rf
    fi
    mkdir sign_apk_tool
    mv target/$1 sign_apk_tool/
    cd sign_apk_tool/
    old_apk=$1
    new_channel=$2
    old_apk_name=`echo $old_apk |awk -F ".apk" '{print $1}'`
    echo old_apk_name=$old_apk_name

    echo ================================apktool decompile===========================
    java -jar $tool_path/apktool.jar d $old_apk #反编译apk
    echo delete $old_apk ...
    rm $old_apk


    #大麦(1)修改apk名字,(2)替换bg_main_video.png(3)替换优化页(4)替换icon(5)替换启动页(6)替换devicename.txt文件(7)删除homepage
    if [ "$2" == "damai_inner" -o "$2" == "damai_oversea" ];then
        echo $2 channel need to change app name and add damai
        sed -i s/app_name\"\>/app_name\"\>Damai/g   $old_apk_name/res/values/strings.xml
        sed -i s/app_name\"\>/app_name\"\>"大麦"/g   $old_apk_name/res/values-zh-rCN/strings.xml
        sed -i s/app_name\"\>/app_name\"\>"大麥"/g   $old_apk_name/res/values-zh-rHK/strings.xml
        sed -i s/app_name\"\>/app_name\"\>"大麥"/g   $old_apk_name/res/values-zh-rTW/strings.xml
        echo change result as follow:
        grep -rn app_name $old_apk_name/res/* |grep -v public.xml

        echo $2 channel need to change water mark name and add damai
        sed -i s/watermark_name\"\>/watermark_name\"\>Damai/g   $old_apk_name/res/values/strings.xml
        sed -i s/watermark_name\"\>/watermark_name\"\>"大麦"/g   $old_apk_name/res/values-zh-rCN/strings.xml
        sed -i s/watermark_name\"\>/watermark_name\"\>"大麥"/g   $old_apk_name/res/values-zh-rHK/strings.xml
        sed -i s/watermark_name\"\>/watermark_name\"\>"大麥"/g   $old_apk_name/res/values-zh-rTW/strings.xml
        echo change result as follow:
        grep -rn watermark_name $old_apk_name/res/* |grep -v public.xml

        echo replace bg_main_video.png_12K and result as follow:
        cp $tool_path/damai/bg_main_video.png $old_apk_name/res/mipmap-xxhdpi-v4/bg_main_video.png
        du -sh  $old_apk_name/res/mipmap-xxhdpi-v4/bg_main_video.png

        echo replace cast_optimize.png_608k and result as follow:
        cp $tool_path/damai/cast_optimize.png $old_apk_name/res/drawable/cast_optimize.png
        du -sh $old_apk_name/res/drawable/cast_optimize.png
        
        echo $2 replace icon_20K and result as follow:
        rm $old_apk_name/res/mipmap-xhdpi-v4/lebo_game_icon.png
        cp $tool_path/damai/damai_icon.png  $old_apk_name/res/mipmap-xhdpi-v4/lebo_game_icon.png
        du -sh $old_apk_name/res/mipmap-xhdpi-v4/lebo_game_icon.png

        echo replace lunch page_104k and result as follow:
        cp $tool_path/damai/damai_lunch_pg.png   $old_apk_name/res/mipmap-xhdpi-v4/lunch_bg.png
        du -sh $old_apk_name/res/mipmap-xhdpi-v4/lunch_bg.png

        echo replace devicename.txt and result as follow:
        cp $tool_path/damai/devicenames.txt   $old_apk_name/res/raw/devicenames.txt
        cat $old_apk_name/res/raw/devicenames.txt
        echo
    fi

    #alibaba修改点：（1）使用不同的图标 （2）修改启动页 （3）修改应用名称:CIBN乐播投屏
    if [ "$2" == "alibaba" ];then
        echo alibaba change to different icon_68k
        rm $old_apk_name/res/mipmap-xhdpi-v4/lebo_game_icon.png
        cp  $tool_path/ali/ali_icon.png  $old_apk_name/res/mipmap-xhdpi-v4/lebo_game_icon.png
        du -sh $old_apk_name/res/mipmap-xhdpi-v4/lebo_game_icon.png

        echo replace lunch page_240k and result as follow:
        cp $tool_path/ali/ali_lunch_pg.png   $old_apk_name/res/mipmap-xhdpi-v4/lunch_bg.png
        du -sh $old_apk_name/res/mipmap-xhdpi-v4/lunch_bg.png

        echo $2 channel need to change app name and add damai
        sed -i s/app_name\"\>/app_name\"\>CIBN/g   $old_apk_name/res/values/strings.xml
        sed -i s/app_name\"\>/app_name\"\>"CIBN"/g   $old_apk_name/res/values-zh-rCN/strings.xml
        sed -i s/app_name\"\>/app_name\"\>"CIBN"/g   $old_apk_name/res/values-zh-rHK/strings.xml
        sed -i s/app_name\"\>/app_name\"\>"CIBN"/g   $old_apk_name/res/values-zh-rTW/strings.xml
        echo change result as follow:
        grep -rn app_name $old_apk_name/res/* |grep -v public.xml
    fi

    #创维盒子修改：
    #（1）应用名称修改为投屏教程
    #（2）投屏优化指南： 将文字中"电视“换成 ”创维盒子“;同时去掉淘宝扫一扫的二维码；电视图像旁边增加创维盒子的图像
    if [ "$2" == "skyworthbox" ];then
        echo $2 need to change app name
        sed -i s/app_name\"\>HappyCast/app_name\"\>"Multi-Screen"/g   $old_apk_name/res/values/strings.xml
        sed -i s/app_name\"\>乐播投屏/app_name\"\>"投屏教程"/g   $old_apk_name/res/values-zh-rCN/strings.xml
        sed -i s/app_name\"\>樂播投屏/app_name\"\>"投屏教程"/g   $old_apk_name/res/values-zh-rHK/strings.xml
        sed -i s/app_name\"\>樂播投屏/app_name\"\>"投屏教程"/g   $old_apk_name/res/values-zh-rTW/strings.xml
        echo change result as follow:
        grep -rn app_name $old_apk_name/res/* |grep -v public.xml
        echo replace cast_optimize.png_608k and result as follow:
        cp $tool_path/skyworthbox/cast_optimize.png $old_apk_name/res/drawable/cast_optimize.png
        du -sh $old_apk_name/res/drawable/cast_optimize.png
        echo replace lunch page_292k and result as follow:
        cp $tool_path/skyworthbox/skyworthbox_lunch_pg.png   $old_apk_name/res/mipmap-xhdpi-v4/lunch_bg.png
        du -sh $old_apk_name/res/mipmap-xhdpi-v4/lunch_bg.png
    fi
    #创米去掉水印，关闭水印开关
    if [ "$2" == "imilab" ]; then
        echo imilab need to close switch_watermark
        sed -i s/switch_watermark\"\>1/switch_watermark\"\>0/g   $old_apk_name/res/values/strings.xml
        echo change result as follow:
        grep -rn "switch_watermark" $old_apk_name/res/values/strings.xml
    fi
    #小米替换icon
    if [ "$2" == "xiaomi" ];then
        echo xiaomi change to different icon_140k
        rm $old_apk_name/res/mipmap-xhdpi-v4/lebo_game_icon.png
        cp  $tool_path/xiaomi/xiaomi_icon.png  $old_apk_name/res/mipmap-xhdpi-v4/lebo_game_icon.png
        du -sh $old_apk_name/res/mipmap-xhdpi-v4/lebo_game_icon.png
    fi
    #坚果升级渠道需要替换应用名称(只给了替换中文简体的需求)
    if [ "$2" == "jianguo_up" ];then
        echo $2 need to change app name
        sed -i s/app_name\"\>乐播投屏/app_name\"\>"乐播投屏升级版"/g   $old_apk_name/res/values-zh-rCN/strings.xml
        echo change result as follow:
        grep -rn app_name $old_apk_name/res/values-zh-rCN/strings.xml
    fi
    #当贝投影修改：（1）app名称为当贝投屏（2）修改启动页 （3）修改icon
    if [ "$2" == "dangbei_touying"  -o "$2" == "dangbei_ty" ];then
        echo $2 need to change app name
        sed -i s/app_name\"\>HappyCast/app_name\"\>"DangbeiCast"/g   $old_apk_name/res/values/strings.xml
        sed -i s/app_name\"\>乐播投屏/app_name\"\>"当贝投屏"/g   $old_apk_name/res/values-zh-rCN/strings.xml
        sed -i s/app_name\"\>樂播投屏/app_name\"\>"當貝投屏"/g   $old_apk_name/res/values-zh-rHK/strings.xml
        sed -i s/app_name\"\>樂播投屏/app_name\"\>"當貝投屏"/g   $old_apk_name/res/values-zh-rTW/strings.xml
        echo change result as follow:
        grep -rn app_name $old_apk_name/res/* |grep -v public.xml
        echo replace dangbei_ty_icon.png_20k and result as follow:
        cp $tool_path/dangbei_ty/dangbei_ty_icon.png $old_apk_name/res/mipmap-xhdpi-v4/lebo_game_icon.png
        du -sh $old_apk_name/res/mipmap-xhdpi-v4/lebo_game_icon.png
        echo replace lunch page_388k and result as follow:
        cp $tool_path/dangbei_ty/dangbei_ty_lunch_pg.png   $old_apk_name/res/mipmap-xhdpi-v4/lunch_bg.png
        du -sh $old_apk_name/res/mipmap-xhdpi-v4/lunch_bg.png
    fi
    #江苏移动修改：（1）修改启动页 （2）去掉镜像水印和视频播放器水印 (3)修改应用名称为“投屏”
    if [ "$2" == "jsyd" ];then
        echo $2 need to change app name
        sed -i s/app_name\"\>HappyCast/app_name\"\>"Cast"/g   $old_apk_name/res/values/strings.xml
        sed -i s/app_name\"\>乐播投屏/app_name\"\>"投屏"/g   $old_apk_name/res/values-zh-rCN/strings.xml
        sed -i s/app_name\"\>樂播投屏/app_name\"\>"投屏"/g   $old_apk_name/res/values-zh-rHK/strings.xml
        sed -i s/app_name\"\>樂播投屏/app_name\"\>"投屏"/g   $old_apk_name/res/values-zh-rTW/strings.xml
        echo change result as follow:
        grep -rn app_name $old_apk_name/res/* |grep -v public.xml
        echo replace lunch page_240k and result as follow:
        cp $tool_path/jsyd/jsyd_lunch.png   $old_apk_name/res/mipmap-xhdpi-v4/lunch_bg.png
        du -sh $old_apk_name/res/mipmap-xhdpi-v4/lunch_bg.png
        echo imilab need to close switch_watermark
        sed -i s/switch_watermark\"\>1/switch_watermark\"\>0/g   $old_apk_name/res/values/strings.xml
        echo change result as follow:
        grep -rn "switch_watermark" $old_apk_name/res/values/strings.xml
    fi
    #替换默认图标为世界杯图标
    #if [ "$2" != "alibaba" -a  "$2" != "damai_inner" -a "$2" != "damai_oversea" ];then
    #    echo $2 channel change to world cup icon
    #    rm $old_apk_name/res/mipmap-xhdpi-v4/lebo_game_icon.png
    #    cp  $tool_path/world_cup.png $old_apk_name/res/mipmap-xhdpi-v4/lebo_game_icon.png
    #fi

    echo ==============================delete META-INF ===================
    rm -rf $old_apk_name/original/META-INF  #删除签名相关文件夹META-INF
    echo ================================apktool compile============================
    java -jar $tool_path/apktool.jar b $old_apk_name #重编译apk
    mv $old_apk_name/dist/$old_apk ./

    #echo setting alias .....
    #keytool -list -v -keystore $tool_path/mirrorcast_aw.key -alias mirrorcast_aw -storepass mirrorcastisgood
    echo ===================================sign====================================
    jarsigner -verbose -digestalg SHA1 -sigalg SHA1withRSA -keystore $tool_path/mirrorcast_aw.key -signedjar "$old_apk_name".apk $old_apk mirrorcast_aw -storepass mirrorcastisgood  #签名

    echo ==================================checking sign=============================
#jarsigner -certs -verbose -verify "$old_apk_name"_signed.apk
    jarsigner -certs -verify "$old_apk_name".apk #检查签名
    mv "$old_apk_name".apk  ../target/"$old_apk_name".apk
    cd ../
    du -sh target/*
    echo cur_path=`pwd`
}

function phoenix_build_leboapk()
{
    echo start build SDK:leboapk.....
    ftp_dst_path=$1
    sdk_dpath=`pwd`
    echo dst dir =$ftp_dst_path and type=$2 and repo=$3
    echo cur_path=$sdk_dpath
    sdk_branch=`cat sdk_branch`
    rec_sdk_tag=`cat build_tags |grep sdk_tag |awk -F "=" '{print $2}'`
    echo sdk_branch=$sdk_branch and sdk_tag=$rec_sdk_tag
    debug_aar_flag="n"
    release_aar_flag="n"
    if [ -f sdk_path ] ;then
        echo have sdk path and will get sdk aar
        mkdir sdk_download
        cat sdk_path > sdk_download/sdk_path_info
        sdk_path=`cat sdk_download/sdk_path_info`
        echo download $sdk_path
    fi
    if [ "x$sdk_path" != "x" ];then #如果有输入sdk路径（主要针对重复app依赖的sdk的问题）
        cd sdk_download
        curl -u aolingli:ALL1234!  $sdk_path > sdk_ftp_f
        cat sdk_ftp_f |grep "<DIR>"  |awk -F " " '{print $4}' > sdk_ftp_info #获取文件夹名（就是sdk）
        for d_aar in `cat  sdk_ftp_info`
            do
                echo download $d_aar
                curl -u aolingli:ALL1234!  $sdk_path"$d_aar"/ > sdk_aar_f #获取debug或者release类型的sdk名字 
                cat sdk_aar_f |grep ".aar" | awk -F " " '{print $4}' > sdk_aar_info
                aar_name=`cat sdk_aar_info`
                echo aar_name=$aar_name
                curl -u aolingli:ALL1234! -o $aar_name  $sdk_path"$d_aar"/$aar_name  #下载对应类型的aar
            done
        [ -f "sdk-leboapk-debug.aar" ] && debug_aar_flag="y" #下载了debug的sdk
        [ -f "sdk-leboapk-release.aar" ] && release_aar_flag="y" #下载了release的sdk
    fi
    echo ++++++++++++++debug_aar_flag=$debug_aar_flag,release_aar_flag=$release_aar_flag+++++++++++++++
    echo used sdk path:`cat $sdk_dpath/sdk_path` > $sdk_dpath/sdk_info
    cd $sdk_dpath
    sdk_aar_path="$sdk_dpath/app/libs/"
    #如果路径中包含debug和release的aar,那么不管type是debug,release,all都不需要编译sdk
    if [ "$debug_aar_flag" == "y" -a "$release_aar_flag" == "y" ];then
            cp -f sdk_download/sdk-leboapk-debug.aar $sdk_aar_path
            cp -f sdk_download/sdk-leboapk-release.aar $sdk_aar_path
            return
    fi
    #如果路径中只有debug的aar,那么type必须要是debug的才不要编译sdk
    if [ "$debug_aar_flag" == "y" -a "$2" == "debug" ];then
        cp -f sdk_download/sdk-leboapk-debug.aar $sdk_aar_path
        return
    fi
    #如果路径中只有relase的aar,那么type必须要是release的才不要编译sdk
    if [ "$release_aar_flag" == "y" -a "$2" == "release" ];then
        cp -f sdk_download/sdk-leboapk-release.aar $sdk_aar_path
        return
    fi
    #其他情况都需要编译sdk
    if [ "$3" == "recsdk" ]; then #新的接收端sdk采用repo管理，所以修改脚本适配repo管理，
        #如果需要打老的app，sdk可以使用老的sdk工程打包leboapk,再app中替换路径中的aar
        #git clone ssh://gerrit@192.168.8.250:29418/phoenix/SDK && cd SDK
        export REPO_URL='https://mirrors.tuna.tsinghua.edu.cn/git/git-repo/'
        if [ "x$rec_sdk_tag" != "x" ];then  #如果指定了sdk的tag,优先使用tag，否则使用分支
            echo use tag:$rec_sdk_tag to get repo 
            repo init -u gerrit:phoenix/manifest -b refs/tags/$rec_sdk_tag
            check_repo tag $rec_sdk_tag #检查tag是否存在
            cd $sdk_dpath
            echo repo config :
            cat .repo/manifest.xml
            repo sync -j4
            repo start $rec_sdk_tag --all
            du -sh
            cd SDK/
            sdk_bname=`echo $rec_sdk_tag |sed 's/\.//g'`
        else 
            echo use branch:$sdk_branch to get repo
            repo init -u gerrit:phoenix/manifest -b $sdk_branch
            #repo init -u ssh://gerrit@192.168.8.250:29418/phoenix/manifest -b $sdk_branch #master jenkins上需要这两条修改
            #sed -i s/"gerrit:"/"ssh:\/\/gerrit@192.168.8.250:29418\/"/g .repo/manifest.xml
            check_repo branch $sdk_branch #检查分支是否存在
            cd $sdk_dpath
            echo repo config :
            cat .repo/manifest.xml
            repo sync -j4
            repo start $sdk_branch --all
            du -sh
            cd SDK/
            sdk_bname=`echo $sdk_branch |sed 's/\.//g'`
        fi 
    fi
    if [ "$3" == "sendsdk" ]; then #发送端sdk采用老的处理方式
        git clone ssh://gerrit@192.168.8.250:29418/phoenix/standard/sdk/"source"
        cd "source"
        if [ "x$rec_sdk_tag" != "x" ];then  #如果指定了sdk的tag,优先使用tag，否则使用分支
            check_tag $rec_sdk_tag
            git checkout $rec_sdk_tag
            sdk_bname=`echo $rec_sdk_tag |sed 's/\.//g'`
        else
            git checkout $sdk_branch
            git pull
            sdk_bname=`echo $sdk_branch |sed 's/\.//g'`
        fi
    fi
    app_pwd=`pwd`
    sdk_commit=`git rev-parse --short HEAD`
    sdk_commit="$sdk_bname"_"$sdk_commit"
    [ "$3" == "recsdk" ] && cp /usr/local/scripts/build_scripts/local.properties android/sink/

    if [ "$2" == "all" ];then
        if [ "$3" == "recsdk" ];then
            if [ "$debug_aar_flag" == "n" ];then #sdk路径中没有debug的aar
                echo start build debug leboapk sdk ...
                sh build.sh "channel:leboapk,onlybuild:0" #构建leboapk debug sdk,debug sdk 不加固
                cp -f target/sdk-leboapk-debug.aar $sdk_aar_path/sdk-leboapk-debug.aar
            else #sdk的路径中有debug的aar
                echo downlod path have debug aar and no need build
                cp -f $sdk_dpath/sdk_download/sdk-leboapk-debug.aar $sdk_aar_path
            fi
        fi
        if [ "$3" == "sendsdk" ];then
            if [ "$debug_aar_flag" == "n" ];then #sdk路径中没有debug的aar
                echo start build debug leboapk sdk ...
                sh build.sh leboapk debug 0 #构建leboapk debug sdk
                cp -f  target/public/sdk-leboapk-debug.aar  $sdk_aar_path/sdk-leboapk-debug.aar
                mv target/public/* target/
                rm target/public -rf
            else #sdk的路径中有debug的aar
                echo downlod path have debug aar and no need build
                cp -f $sdk_dpath/sdk_download/sdk-leboapk-debug.aar $sdk_aar_path
            fi
        fi
        [ "$debug_aar_flag" == "n" ] && upload_file $ftp_dst_path sdk_leboapk_debug_$sdk_commit  #上传到ftp

        cd $app_pwd
        if [ "$3" == "recsdk" ];then
            if [ "$release_aar_flag"  == "n" ];then #sdk 路径中没release的aar
                echo start build release leboapk sdk ...
                sh build.sh "channel:leboapk,buildtype:release,onlybuild:0" #构建leboapk release sdk
                cp -f target/sdk-leboapk-release.aar $sdk_aar_path/sdk-leboapk-release.aar
            else #sdk的路径中有release的aar
                echo downlod path have release aar and no need build
                cp -f $sdk_dpath/sdk_download/sdk-leboapk-release.aar $sdk_aar_path
            fi
        fi
        if [ "$3" == "sendsdk" ];then
            if [ "$release_aar_flag"  == "n" ];then #sdk 路径中没意义release的aar
                echo start build release leboapk sdk ...
                sh build.sh leboapk release 0  #构建leboapk release sdk
                cp -f  target/public/sdk-leboapk-release.aar  $sdk_aar_path/sdk-leboapk-release.aar
                mv target/public/* target/
                rm target/public -rf
            else #sdk的路径中有release的aar
                echo downlod path have  release aar and no need build
                cp -f $sdk_dpath/sdk_download/sdk-leboapk-release.aar $sdk_aar_path
            fi
        fi
        [ "$release_aar_flag" == "n" ] && upload_file $ftp_dst_path sdk_leboapk_release_$sdk_commit #上传到ftp
    fi

    if [ "$2" == "debug" -o "$2" == "release" ];then
        if [ "$3" == "recsdk" ];then
            sh build.sh "channel:leboapk,buildtype:$2,onlybuild:0"
            cp -f target/sdk-leboapk-"$2".aar $sdk_aar_path/sdk-leboapk-"$2".aar
        fi
        if [ "$3" == "sendsdk" ];then
            sh build.sh leboapk $2 0
            cp -f  target/public/sdk-leboapk-"$2".aar  $sdk_aar_path/sdk-leboapk-"$2".aar
            mv target/public/* target/
            rm target/public -rf
        fi
        upload_file $ftp_dst_path sdk_leboapk_"$2"_$sdk_commit
    fi

    cd $app_pwd
    if [ "$3" == "recsdk" ];then  #获取sdk的信息
        echo "read sdk version for SDK/android/sink/build.gradle" >> $sdk_dpath/sdk_info
        sed -n 41p android/sink/build.gradle >> $sdk_dpath/sdk_info
        sed -n 42p android/sink/build.gradle >> $sdk_dpath/sdk_info
        echo sdk_branch=$sdk_branch >> $sdk_dpath/sdk_info
        echo sdk_tag=$rec_sdk_tag >> $sdk_dpath/sdk_info
        echo AndroidReceiver SDK use all interfaces >> $sdk_dpath/sdk_info
        echo ========repos branches========= >> $sdk_dpath/sdk_info
        cat $sdk_dpath/.repo/manifest.xml |grep project |awk -F "project " '{print $2}' |awk -F "name=" '{print $1}' |sed s/"\""//g >> $sdk_dpath/sdk_info
        sdk_repo="SDK SDK/base/upnp SDK/android/sink/sdk-api SDK/android/sink/common SDK/android/sink/SDK-sample"
        echo ========repos commit id========= >> $sdk_dpath/sdk_info
        for repo_p in $sdk_repo
        do
            cd $sdk_dpath/$repo_p
            echo $repo_p commit id=`git rev-parse HEAD` >> $sdk_dpath/sdk_info
        done
        echo "feature.dat(sdk-api/src/main/assets/hpplay/dat/feature.dat) interfaces as follow:" >> $sdk_dpath/sdk_info
        cat $sdk_dpath/SDK/android/sink/sdk-api/src/main/assets/hpplay/dat/feature.dat >> $sdk_dpath/sdk_info
    fi
    if [ "$3" == "sendsdk" ];then #获取sdk信息
        echo "read sdk version for source/build.gradle" >> $sdk_dpath/sdk_info
        grep -r "versionCode" build.gradle >> $sdk_dpath/sdk_info
        grep -r "versionName" build.gradle >> $sdk_dpath/sdk_info
        echo commit ID :`git rev-parse HEAD` >> $sdk_dpath/sdk_info
    fi
    echo ====================phoenix sdk $sdk_bname build done =================
    cd $sdk_dpath/
}

function check_tag
{
    echo input tag is $1
    tag_falg=`git tag |grep $1`
    if [ "x$tag_falg" == "x" ];then
        echo have no this tag:$1 and please check again as follow:
        git tag
        exit 1
    else
        echo have input tag:$1
    fi
}

function deal_with_phoenix
{
    deal_type=$1
    deal_channel=$2
    deal_repo=$3
    echo "***************type=$deal_type,channle=$deal_channel,repo=$deal_repo*****************"
    cp bak_target/"hpplay-happytest-$deal_type"*.apk target/
    app_name=`ls target |grep "hpplay-happytest-$deal_type" `
    echo app_name=$app_name
    if [ "$deal_channel" == "happytest" ];then
        echo happytest channle have no need modify name
    else
        if [ "$deal_repo" == "rec_app" -o "$deal_repo" == "rec_app_tob" ] ; then
            phoenix_app_special_channels $app_name $deal_channel
            replace_channel_conf $app_name $deal_channel rec_app_info.conf $deal_repo
        else
            replace_channel_conf $app_name $deal_channel send_app_info.conf $deal_repo
        fi
        rm target/hpplay-happytest* -rf
    fi
}

function check_repo()
{
    echo will check $1 $2
    if [ -d .repo/manifests.git ]; then
        cd .repo/manifests.git
        [ "$1" == "tag" ] && [ "x`git tag |grep $2`" == "x" ] && echo tag $2 is not exist && exit 1
        [ "$1" == "branch" ] && [ "x`git branch -a |grep $2`" == "x" ] && echo branch $2 is not exist && exit 1
        [ "$1" != "tag" -a "$1" != "branch" ] && echo check repo failed && exit 1
    else
        echo .repo/manifests.git is not exist and exit
        exit 1
    fi
}
